<template>
  <view class="user-page">
    <!-- 全局发布弹框 -->
    <PublishModal ref="publishModalRef" />
    <header class="header">
      <image class="header-image" src="/static/header-bg.png" mode="aspectFill"></image>
    </header>
     <view class="user-profile-container">
      <!-- 用户信息区域 -->
      <view class="user-info-section">
        <view class="user-profile">
          <image class="avatar" :src="userInfo.avatar" mode="aspectFill" @click="goToProfile"></image>
          <view class="user-details">
            <view class="name-row">
              <text class="username">{{ userInfo.name }}</text>
              <view class="verified-tag" :class="{ unverified: userInfo.isFamous !== 1 }" @click="goToVerify">
                <text>{{ userInfo.isFamous === 1 ? '已实名' : '未实名' }}</text>
              </view>
            </view>
            <text class="user-id">ID {{ userInfo.id }}</text>
          </view>
          <view class="settings-icon" @click="goToSettings">
            <image class="settings-image" src="/static/settings-icon.png" mode="aspectFit"></image>
          </view>
        </view>
      </view>

      <!-- 统计数据区域 -->
      <view class="stats-section">
        <view class="stat-item" @click="goToWallet">
          <text class="stat-number">{{ userInfo.balance }}</text>
          <text class="stat-label">钱包</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item" @click="goToFollowing">
          <text class="stat-number">{{ userInfo.followCount }}</text>
          <text class="stat-label">关注</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item" @click="goToFans">
          <text class="stat-number">{{ userInfo.fansCount }}</text>
          <text class="stat-label">粉丝</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-item" @click="goToCollection">
          <text class="stat-number">{{ userInfo.stats.collection }}</text>
          <text class="stat-label">收藏</text>
        </view>
      </view>
    </view>


    <!-- 菜单列表 -->
    <view class="menu-section">
      <view class="menu-item" @click="goToMyMoments">
        <view class="menu-icon">
          <image class="menu-image" src="/static/moments-icon.png" mode="aspectFit"></image>
        </view>
        <text class="menu-text">我的朋友圈</text>
        <image class="arrow-image" src="/static/arrow-icon.png" mode="aspectFit"></image>
      </view>
      
      <view class="menu-item" @click="goToMyInvitations">
        <view class="menu-icon">
          <image class="menu-image" src="/static/invitation-icon.png" mode="aspectFit"></image>
        </view>
        <text class="menu-text">我的邀请</text>
        <image class="arrow-image" src="/static/arrow-icon.png" mode="aspectFit"></image>
      </view>
      
      <view class="menu-item" @click="goToAgentCenter">
        <view class="menu-icon">
          <image class="menu-image" src="/static/agent-icon.png" mode="aspectFit"></image>
        </view>
        <text class="menu-text">代理中心</text>
        <image class="arrow-image" src="/static/arrow-icon.png" mode="aspectFit"></image>
      </view>
      
      <view class="menu-item" @click="goToAboutUs">
        <view class="menu-icon">
          <image class="menu-image" src="/static/about-icon.png" mode="aspectFit"></image>
        </view>
        <text class="menu-text">关于我们</text>
        <image class="arrow-image" src="/static/arrow-icon.png" mode="aspectFit"></image>
      </view>
      
      <view class="menu-item" @click="goToCustomerService">
        <view class="menu-icon">
          <image class="menu-image" src="/static/service-icon.png" mode="aspectFit"></image>
        </view>
        <text class="menu-text">联系客服</text>
        <image class="arrow-image" src="/static/arrow-icon.png" mode="aspectFit"></image>
      </view>
    </view>
  </view>
  
  <!-- 自定义底部导航 -->
  <CustomTabBar />
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { onShow } from '@dcloudio/uni-app'
import CustomTabBar from '../components/CustomTabBar.vue'
import UserApi from '@/sheep/api/member/user'
import sheep from '@/sheep'
import PublishModal from '@/pages/components/PublishModal.vue'

// 用户信息数据（初始化占位）
const userInfo = ref({
  avatar: '/static/logo.png',
  name: '',
  id: '',
  isFamous: 0,
  balance: 0,
  followCount: 0,
  fansCount: 0,
  stats: {
    wallet: 0,
    following: 0,
    fans: 0,
    collection: 0
  }
})

// 拉取后端用户信息并映射字段（加防抖防重复）
let isFetchingUser = false
let lastFetchTime = 0
const loadUserInfo = async () => {
  const now = Date.now()
  if (isFetchingUser || now - lastFetchTime < 800) {
    return
  }
  isFetchingUser = true
  try {
    const res = await UserApi.getUserInfo()
    if (!res || res.code !== 0 || !res.data) return
    const d = res.data
    userInfo.value = {
      avatar: d.avatar || '/static/logo.png',
      name: d.nickname || d.username || '',
      id: d.id,
      isFamous: d.isFamous || 0,
      balance: d.balance ?? 0,
      followCount: d.followCount ?? 0,
      fansCount: d.fansCount ?? 0,
      stats: {
        wallet: d.balance ?? 0,
        following: d.followCount ?? 0,
        fans: d.fansCount ?? 0,
        collection: 0
      }
    }
  } catch (e) {
    // 静默失败
  } finally {
    lastFetchTime = Date.now()
    isFetchingUser = false
  }
}

// 跳转到个人资料页面
const goToProfile = () => {
  uni.navigateTo({
    url: '/pages/user/info'
  })
}

// 跳转到设置页面
const goToSettings = () => {
  uni.navigateTo({
    url: '/pages/public/setting'
  })
}

// 跳转到钱包页面
const goToWallet = () => {
  uni.navigateTo({
    url: '/pages/user/wallet'
  })
}

// 跳转到关注页面
const goToFollowing = () => {
  uni.navigateTo({
    url: '/pages/user/following'
  })
}

// 跳转到粉丝页面
const goToFans = () => {
  uni.navigateTo({
    url: '/pages/user/fans'
  })
}

// 跳转到收藏页面
const goToCollection = () => {
  uni.navigateTo({
    url: '/pages/collection/index'
  })
}

// 跳转到我的朋友圈
const goToMyMoments = () => {
  uni.navigateTo({
    url: '/pages/user/my-moments'
  })
}

// 跳转到我的邀请
const goToMyInvitations = () => {
  uni.navigateTo({
    url: '/pages/user/invite'
  })
}

// 跳转到代理中心
const goToAgentCenter = () => {
  uni.navigateTo({
    url: '/pages/user/agent'
  })
}

// 跳转到关于我们
const goToAboutUs = () => {
  uni.navigateTo({
    url: '/pages/user/about'
  })
}

// 跳转到联系客服
const goToCustomerService = () => {
  uni.navigateTo({
    url: '/pages/customer-service/index'
  })
}

// 跳转到实名认证页面
const goToVerify = () => {
  if (userInfo.value.isFamous !== 1) {
    uni.navigateTo({ url: '/pages/user/verify' })
  }
}

const publishModalRef = ref(null)

onMounted(() => {
  uni.$on('showPublishModal', () => {
    publishModalRef.value?.showModal && publishModalRef.value.showModal()
  })
})

onUnmounted(() => {
  uni.$off('showPublishModal')
})

// onMounted 阶段不请求，避免与 onShow 重复触发

onShow(() => {
  // 检查登录状态
  if (!sheep.$store('user').isLogin) {
    console.log('用户未登录，跳转到登录页')
    uni.reLaunch({
      url: '/pages/index/login'
    })
    return
  }
  
  // 页面显示时更新用户数据
  loadUserInfo()
})
</script>

<style lang="scss" scoped>
.user-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding-bottom: calc(98rpx + env(safe-area-inset-bottom));
  padding-bottom: calc(98rpx + constant(safe-area-inset-bottom));
}

.header {
  position: relative;
  padding: 32rpx 0 48rpx;
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 50%, #f0e6ff 100%);
  overflow: hidden;
  height: 280rpx;
  z-index: 0;
}

.header-image {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: -2;
}

.user-profile-container {
  margin: -188rpx 20rpx 20rpx;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 1;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 20rpx;
  background-color: transparent;
  
  .time {
    font-size: 24rpx;
    font-weight: 600;
    color: #000;
  }
  
  .status-icons {
    display: flex;
    align-items: center;
    gap: 8rpx;
    
    .signal, .wifi, .battery {
      font-size: 20rpx;
      color: #000;
    }
  }
}

.user-info-section {
  padding: 40rpx 30rpx 30rpx;
  
  .user-profile {
    display: flex;
    align-items: center;
    gap: 20rpx;
    
    .avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 60rpx;
      border: 4rpx solid #fff;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    }
    
    .user-details {
      flex: 1;
      
      .name-row {
        display: flex;
        align-items: center;
        gap: 12rpx;
        margin-bottom: 8rpx;
        
        .username {
          font-size: 32rpx;
          font-weight: 600;
          color: #000;
        }
        
        .verified-tag {
          background: linear-gradient(135deg, #ff6b35, #f7931e);
          padding: 4rpx 12rpx;
          border-radius: 12rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          height: 32rpx;
          
          text {
            font-size: 20rpx;
            color: #fff;
            font-weight: 500;
            line-height: 1;
          }
        }
        .verified-tag.unverified {
          background: #e5e7eb; /* 灰色背景 */
        }
      }
      
      .user-id {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .settings-icon {
      margin-top: -60rpx;
      
      .settings-image {
        width: 50rpx;
        height: 50rpx;
      }
    }
  }
}

.stats-section {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-top: 1rpx solid #f5f5f5;
  
  .stat-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
    
    .stat-number {
      font-size: 36rpx;
      font-weight: 600;
      color: #000;
    }
    
    .stat-label {
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .stat-divider {
    width: 2rpx;
    height: 60rpx;
    background: #f0f0f0;
  }
}

.menu-section {
  background: #fff;
  margin: 0 20rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .menu-item {
    display: flex;
    align-items: center;
    padding: 40rpx;
    position: relative;
    
    &:last-child {
      border-bottom: none;
    }
    
    &:not(:last-child)::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 40rpx;
      right: 40rpx;
      height: 1rpx;
      background-color: #f5f5f5;
    }

    .menu-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
      
      .menu-image {
        width: 35rpx;
        height: 35rpx;
      }
    }
    
    .menu-text {
      flex: 1;
      font-size: 28rpx;
      color: #000;
      font-weight: 500;
    }
    
    .arrow-image {
      width: 50rpx;
      height: 50rpx;
    }
  }
}
</style>
